package org.dylan.web.tag.script;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang3.StringUtils;
import org.dylan.core.util.SystemUtil;
import org.dylan.web.util.ResponseUtil;

/**
 * 脚本输出标签
 * 
 * @author dylan
 * 
 */
public class ScriptTag extends TagSupport {
	private static final long serialVersionUID = 6049675725736615829L;
	private Map<String, ScriptModel> scriptMap;
	private String id;
	private boolean debug;
	private String path;
	private String context;
	private boolean useContextPath = true;

	public ScriptTag() {
		scriptMap = ScriptDefineParser.scripts();
		debug = SystemUtil.debugModel();
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public boolean isDebug() {
		return debug;
	}

	public void setDebug(boolean debug) {
		this.debug = debug;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getContext() {
		return context;
	}

	public void setContext(String context) {
		this.context = context;
	}

	public boolean isUseContextPath() {
		return useContextPath;
	}

	public void setUseContextPath(boolean useContextPath) {
		this.useContextPath = useContextPath;
	}

	@Override
	public int doStartTag() throws JspException {
		return EVAL_PAGE;
	}

	@Override
	public int doEndTag() throws JspException {
		if (StringUtils.isBlank(context)) {
			context = ((HttpServletRequest) pageContext.getRequest())
					.getContextPath();
		}
		if (StringUtils.isNotEmpty(path)) {
			writeScripts(path);
		} else if (StringUtils.isNotBlank(id)) {
			String[] types = id.split(",");
			for (String type : types) {
				type = type.trim();
				writeDefinedScripts(type);
			}
		}
		return super.doEndTag();
	}

	/**
	 * 输出预定义过的js脚本
	 * 
	 * @param type
	 */
	private void writeDefinedScripts(String type) {
		if (scriptMap.containsKey(type)) {
			ScriptModel model = scriptMap.get(type);
			String scripts = debug ? model.getDebugPath() : model.getPath();
			writeScripts(scripts);
		}
	}

	/**
	 * 输出多个脚本文件，文件之间以逗号分隔
	 * 
	 * @param scripts
	 */
	private void writeScripts(String scripts) {
		if (scripts == null) {
			return;
		}
		String[] scriptArr = scripts.split(",");
		for (String script : scriptArr) {
			writeScript(script);
		}
	}

	/**
	 * 输入脚本文件
	 * 
	 * @param script
	 */
	private void writeScript(String script) {
		if (StringUtils.isBlank(script)) {
			return;
		}
		if (!context.endsWith("/")) {
			context += "/";
		}
		// JspWriter writer = pageContext.getResponse();
		script = script.trim();
		if (isUseContextPath()) {
			script = context + script;
		}
		ResponseUtil.writeScript(pageContext, script);
	}
}
